package com.example.springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.springboot.controller.dto.UserDTO;
import com.example.springboot.controller.dto.UserPasswordDTO;
import com.example.springboot.entity.dto.req.UserLoginAndBindReqDTO;
import com.example.springboot.entity.dto.resp.LoginAndBindRespDTO;
import com.example.springboot.entity.dto.resp.UserRespDTO;
import com.example.springboot.entity.dto.resp.WxLoginRespDTO;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.common.Constants;
import com.example.springboot.common.RoleEnum;
import com.example.springboot.entity.Menu;
import com.example.springboot.entity.User;
import com.example.springboot.mapper.RoleMapper;
import com.example.springboot.mapper.RoleMenuMapper;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.IMenuService;
import com.example.springboot.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author
 * @since 2022-01-26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private static final Log LOG = Log.get();

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private IMenuService menuService;

    @Value("${wx.mp.appid}")
    private String appid;

    @Value("${wx.mp.appSecret}")
    private String appSecret;


    @Override
    public LoginAndBindRespDTO loginAndBind(UserLoginAndBindReqDTO requestParam) {
        User one = getUserInfo(requestParam);
        if (Objects.equals(one.getIsDisabled(), "1")) {
            throw new ServiceException(Constants.CODE_700, "当前访问权限不够，请联系管理员");
        }
        one.setOpenid(requestParam.getOpenId());
        baseMapper.updateById(one);
        // 设置token
        String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
        return LoginAndBindRespDTO.builder()
                .nickname(one.getNickname())
                .isSubscribe(one.getIsSubscribe())
                .isFileSubscribe(one.getIsFileSubscribe())
                .userid(String.valueOf(one.getId()))
                .token(token)
                .build();
    }

    public UserRespDTO login(UserDTO userDTO) {
        UserRespDTO userRespDTO = new UserRespDTO();
        User one = getUserInfo(userDTO);
        if (Objects.equals(one.getIsDisabled(), "1")) {
            throw new ServiceException(Constants.CODE_700, "当前访问权限不够，请联系管理员");
        }
        if (userDTO.getCode() != null) {
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid
                    + "&secret=" + appSecret
                    + "&js_code=" + userDTO.getCode()
                    + "&grant_type=authorization_code";
            RestTemplate restTemplate = new RestTemplate();

            try {
                String response = restTemplate.getForObject(url, String.class);
                JSONObject jsonObject = JSONUtil.parseObj(response);
                // 检查是否存在错误码
                if (jsonObject.containsKey("errcode")) {
                    String errmsg = jsonObject.getStr("errmsg");
                    System.out.println("Error from WeChat API: " + errmsg);
                    throw new ServiceException(jsonObject.getStr("errcode"), errmsg);
                }

                String openid = jsonObject.getStr("openid");
                if (StrUtil.isNotBlank(openid)) {
                    one.setOpenid(openid);
                    baseMapper.updateById(one);
                }
                BeanUtil.copyProperties(one, userRespDTO, true);
                // 设置token
                String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
                userRespDTO.setToken(token);

                String role = one.getRole(); // ROLE_ADMIN
                // 设置用户的菜单列表
                List<Menu> roleMenus = getRoleMenus(role);
                userRespDTO.setMenus(roleMenus);
                userRespDTO.setIsSubscribe(Objects.equals(userRespDTO.getIsSubscribe(), null) ? "0" : userRespDTO.getIsSubscribe());
                userRespDTO.setIsFileSubscribe(Objects.equals(userRespDTO.getIsFileSubscribe(), null) ? "0" : userRespDTO.getIsFileSubscribe());
                return userRespDTO;
            } catch (Exception e) {
                System.out.println("Exception occurred during WeChat API call: " + e.getMessage());
                throw new ServiceException(Constants.CODE_500, "Internal server error");
            }
        } else {
            BeanUtil.copyProperties(one, userRespDTO, true);
            // 设置token
            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            userRespDTO.setToken(token);

            String role = one.getRole(); // ROLE_ADMIN
            // 设置用户的菜单列表
            List<Menu> roleMenus = getRoleMenus(role);
            userRespDTO.setMenus(roleMenus);
            userRespDTO.setIsSubscribe(Objects.equals(userRespDTO.getIsSubscribe(), null) ? "0" : userRespDTO.getIsSubscribe());
            userRespDTO.setIsFileSubscribe(Objects.equals(userRespDTO.getIsFileSubscribe(), null) ? "0" : userRespDTO.getIsFileSubscribe());
            return userRespDTO;
        }
    }

    @Override
    public WxLoginRespDTO wxLoginService(String code) {
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid
                    + "&secret=" + appSecret
                    + "&js_code=" + code
                    + "&grant_type=authorization_code";
            RestTemplate restTemplate = new RestTemplate();
            String response = restTemplate.getForObject(url, String.class);
            JSONObject jsonObject = JSONUtil.parseObj(response);
            // 检查是否存在错误码
            if (jsonObject.containsKey("errcode")) {
                String errmsg = jsonObject.getStr("errmsg");
                System.out.println("Error from WeChat API: " + errmsg);
                throw new ServiceException(jsonObject.getStr("errcode"), errmsg);
            }

            String openid = jsonObject.getStr("openid");
            if (StrUtil.isNotBlank(openid)) {
                return WxLoginRespDTO.builder()
                        .needLogin(1)
                        .openId(openid)
                        .build();
            }
            throw new ServiceException(Constants.CODE_500,"code失效");

        }catch (Exception e){
            System.out.println("Exception occurred during WeChat API call: " + e.getMessage());
            throw new ServiceException(Constants.CODE_500, e.getMessage());
        }

    }



    @Override
    public User register(UserDTO userDTO) {
        User one = getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, userDTO.getUsername()));
        if (one == null) {
            one = new User();
            BeanUtil.copyProperties(userDTO, one, true);
            // 默认一个普通用户的角色
            one.setRole(RoleEnum.ROLE_USER.toString());
            save(one);  // 把 copy完之后的用户对象存储到数据库
        } else {
            throw new ServiceException(Constants.CODE_600, "用户已存在");
        }
        return one;
    }

    @Override
    public void updatePassword(UserPasswordDTO userPasswordDTO) {
        int update = userMapper.updatePassword(userPasswordDTO);
        if (update < 1) {
            throw new ServiceException(Constants.CODE_600, "密码错误");
        }
    }

    @Override
    public UserRespDTO adminLogin(UserDTO userDTO) {
        UserRespDTO userRespDTO = new UserRespDTO();
        User one = getUserInfo(userDTO);
        if (Objects.equals(one.getIsDisabled(), "1")) {
            throw new ServiceException(Constants.CODE_700, "当前访问权限不够，请联系管理员");
        }
        BeanUtil.copyProperties(one, userRespDTO, true);
        // 设置token
        String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
        userRespDTO.setToken(token);

        String role = one.getRole(); // ROLE_ADMIN
        // 设置用户的菜单列表
        List<Menu> roleMenus = getRoleMenus(role);
        userRespDTO.setMenus(roleMenus);
        userRespDTO.setIsSubscribe(Objects.equals(userRespDTO.getIsSubscribe(), null) ? "0" : userRespDTO.getIsSubscribe());
        userRespDTO.setIsFileSubscribe(Objects.equals(userRespDTO.getIsFileSubscribe(), null) ? "0" : userRespDTO.getIsFileSubscribe());
        return userRespDTO;
    }


    private User getUserInfo(UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", userDTO.getPassword());
        User one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        if (one == null) {
            throw new ServiceException(Constants.CODE_600, "账号密码错误");
        }
        return one;
    }

    private User getUserInfo(UserLoginAndBindReqDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", userDTO.getPassword());
        User one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        if (one == null) {
            throw new ServiceException(Constants.CODE_600, "账号密码错误");
        }
        return one;
    }

    /**
     * 获取当前角色的菜单列表
     *
     * @param roleFlag
     * @return
     */
    private List<Menu> getRoleMenus(String roleFlag) {
        Integer roleId = roleMapper.selectByFlag(roleFlag);
        // 当前角色的所有菜单id集合
        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);

        // 查出系统所有的菜单(树形)
        List<Menu> menus = menuService.findMenus("");
        // new一个最后筛选完成之后的list
        List<Menu> roleMenus = new ArrayList<>();
        // 筛选当前用户角色的菜单
        for (Menu menu : menus) {
            if (menuIds.contains(menu.getId())) {
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();
            // removeIf()  移除 children 里面不在 menuIds集合中的 元素
            children.removeIf(child -> !menuIds.contains(child.getId()));
        }
        return roleMenus;
    }

}
